package com.weitu.workflow.definition.handler;

import com.weitu.workflow.definition.constant.FlowDefConstants;
import org.fireflow.engine.EngineException;
import org.fireflow.engine.IProcessInstance;
import org.fireflow.engine.IWorkItem;
import org.fireflow.engine.impl.TaskInstance;
import org.fireflow.engine.taskinstance.IAssignable;
import org.fireflow.engine.taskinstance.IAssignmentHandler;
import org.fireflow.kernel.IToken;
import org.fireflow.kernel.KernelException;
import org.fireflow.model.net.StartNode;

/**
 * 该AssignmentHandler将TaskInstance分配给当前用户，并且立即结束新创建的workitem。适用于填写请假单环节。
 * 
 * @author app
 *
 */
public class DefaultUserAssignmentHandler implements IAssignmentHandler {

	public void assign(IAssignable asignable, String performerName) throws EngineException, KernelException {
		TaskInstance taskInstance = (TaskInstance) asignable;//任务实例
		IProcessInstance processInstance = taskInstance.getAliveProcessInstance();//流程实例

		String activityId = taskInstance.getActivity().getId();//当前环节activityId
		String fromActivityId = taskInstance.getFromActivityId();//前一环节id
		String users = "";
		StartNode s = processInstance.getWorkflowProcess().getStartNode();
		//如果为第一处理环节
		if (fromActivityId.equals(IToken.FROM_START_NODE) ) {
			processInstance.setProcessInstanceVariable(FlowDefConstants.FLOW_FIRSTACTIVITY_ID,activityId);//设置第一环节节点id
			IWorkItem workItem = asignable.asignToActor(processInstance.getCreatorId());
			workItem.claim();
			workItem.complete();

		}else{
			if (processInstance.getProcessInstanceVariable(activityId)==null&&processInstance.getProcessInstanceVariable(FlowDefConstants.FLOW_FIRSTACTIVITY_ID)!=null&&fromActivityId.equalsIgnoreCase(processInstance.getProcessInstanceVariable(FlowDefConstants.FLOW_FIRSTACTIVITY_ID).toString())&& processInstance.getProcessInstanceVariable(FlowDefConstants.FLOW_FIRSTUSER_ID) != null){
				//第二环节
				users = processInstance.getProcessInstanceVariable(FlowDefConstants.FLOW_FIRSTUSER_ID).toString();//环节处理人

			}
			if ((users == null || "".equals(users)) && processInstance.getProcessInstanceVariable(activityId) != null) {
				users = processInstance.getProcessInstanceVariable(activityId).toString();//环节处理人
			}
			boolean dynmic = false;
			if (users != null && !"".equals(users)) {
				if (users != null && !"".equals(users)) {
					String[] user = users.split(",");
					for (int i = 0; i < user.length; i++) {
						IWorkItem workItem = asignable.asignToActor(user[i]);
					}
					dynmic = true;
				}
			}
			if (!dynmic) {
				String currentUser = processInstance.getCreatorId();
				IWorkItem workItem = asignable.asignToActor(currentUser);
				//workItem.claim();
			}
		}
	}

	
}
